package org.fcitmuk.purcai.forms;

import org.fcitmuk.communication.TransportLayer;
import org.fcitmuk.epihandy.RequestHeader;
import org.fcitmuk.epihandy.ResponseHeader;
import org.fcitmuk.epihandy.StudyDef;
import org.fcitmuk.epihandy.StudyDefList;

public class OpenclinicaTransportLayer  extends TransportLayer{
	
	private final static byte CON_TYPE_TESTING = 6;
	
	public OpenclinicaTransportLayer(){
		super();
	}
	
	protected void initConnectionTypes(){
		super.initConnectionTypes();
		addConnectionType(CON_TYPE_TESTING, "Testing");
	}
	
	protected void handleRequest() {
		if(this.getConType() == CON_TYPE_TESTING)
			handleTestConnectionType();
		else
			super.handleRequest();
	}
	
	private void handleTestConnectionType(){
		try{
			int action = ((RequestHeader)dataInParams).getAction();

			if(action == RequestHeader.ACTION_DOWNLOAD_STUDY_LIST)
				downloadStudies();

			if(this.isDownload)
				getEventListener().downloaded(dataOutParams,dataOut);
			else
				getEventListener().uploaded(dataOutParams,dataOut);
		}
		catch(Exception e){
			e.printStackTrace();
			getEventListener().errorOccured(e.getMessage(), e);
		}
	}
	
	private void downloadStudies(){
		StudyDefList studyDefList = new StudyDefList();
		studyDefList.addStudy(new StudyDef((byte)1,"Testing","testing"));
		dataOut = studyDefList;
		((ResponseHeader)dataOutParams).setStatus((dataOut != null) ? ResponseHeader.STATUS_SUCCESS : ResponseHeader.STATUS_ERROR);
	}
}
